package com.ccx.mytemplate.util;

import java.util.List;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFChart;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTNumVal;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrData;
import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrVal;
import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;

public class WordUtil {

    public static XWPFDocument data2Word(Map<String, Object> data, String fileName) {
        try {
            XWPFDocument doc = new XWPFDocument(WordUtil.class.getResourceAsStream(fileName));
            // 替换图表数据
            List<XWPFChart> charts = doc.getCharts();
            for (var chart : charts) {
                String title = getChartTitle(chart);
                if (data.containsKey(title)) {
                    Map<String, Object> item = (Map<String, Object>) data.get(title);
                    Object[] chartSeries = getChartSeries(chart);
                    CTStrData serCat = (CTStrData)chartSeries[0];
                    serCat.setPtArray(new CTStrVal[0]);
                    List<String> cats = (List<String>) item.get("cats");
                    for (int i = 0; i < cats.size(); i++) {
                        CTStrVal strVal = serCat.addNewPt();
                        strVal.setIdx(i);
                        strVal.setV(cats.get(i));
                    }
                    serCat.getPtCount().setVal(cats.size());
                    CTNumData serVal = (CTNumData)chartSeries[1];
                    serVal.setPtArray(new CTNumVal[0]);
                    List<? extends Number> vals = (List<? extends Number>) item.get("vals");
                    for (int i = 0; i < vals.size(); i++) {
                        CTNumVal numVal = serVal.addNewPt();
                        numVal.setIdx(i);
                        numVal.setV(String.valueOf(vals.get(i)));
                    }
                    serVal.getPtCount().setVal(cats.size());
                }
            }
            // 替换文本数据
            var paragraphs = doc.getParagraphs();
            for (var para : paragraphs) {
                for (var entry : data.entrySet()) {
                    String key = "{{" + entry.getKey() + "}}";
                    List<XWPFRun> runs = para.getRuns();
                    for (XWPFRun r : runs) {
                        String text = r.getText(0);
                        if (text != null && text.contains(key)) {
                            text = text.replace(key, entry.getValue() != null ? entry.getValue().toString() : "");
                            r.setText(text, 0);
                        }
                    }
                }
            }
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Object[] getChartSeries(XWPFChart chart) {
        var plotArea = chart.getCTChart().getPlotArea();
        if (plotArea.getBarChartArray().length > 0) {
            return new Object[]{plotArea.getBarChartArray(0).getSerArray(0).getCat().getStrRef().getStrCache(),
                    plotArea.getBarChartArray(0).getSerArray(0).getVal().getNumRef().getNumCache()};
        } else if (plotArea.getLineChartArray().length > 0) {
            return new Object[]{plotArea.getLineChartArray(0).getSerArray(0).getCat().getStrRef().getStrCache(),
                    plotArea.getLineChartArray(0).getSerArray(0).getVal().getNumRef().getNumCache()};
        } else if (plotArea.getPieChartArray().length > 0) {
            return new Object[]{plotArea.getPieChartArray(0).getSerArray(0).getCat().getStrRef().getStrCache(),
                    plotArea.getPieChartArray(0).getSerArray(0).getVal().getNumRef().getNumCache()};
        }
        return null;
    }

    public static String getChartTitle(XWPFChart chart) {
        CTRegularTextRun[] rArray = chart.getCTChart().getTitle().getTx().getRich().getPArray(0).getRArray();
        StringBuilder title = new StringBuilder();
        for (CTRegularTextRun r : rArray) {
            title.append(r.getT());
        }
        return title.toString();
    }

    public static void main(String[] args) {
        var data = Map.of(
            "dataSum", (Object)"1000",
            "今日数据增长趋势", Map.of(
                "cats", List.of("一月", "二月", "三月", "四月", "五月", "六月")
                ,"vals", List.of(100, 200, 150, 300, 250, 400)
                ),
            "近7日数据增长趋势", Map.of(
                "cats", List.of("一月", "二月", "三月", "四月", "五月", "六月")
                ,"vals", List.of(100, 200, 150, 300, 250, 400)
                )
        );
        var doc = data2Word(data, "/static/记录统计.docx");
        try (var out = new java.io.FileOutputStream("D:/proj/git/mytemplate/测试.docx")) {
            doc.write(out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
